/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : booking_view.js                                 
*  Description  : 부킹게시판 글상세 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-05-03  김효순    Created.  
*  2012-05-03  김효순    Complete.  
*******************************************************************************/

jQuery(function($){
	// 상단 타이틀
	function clsBookingTitle()
	{
		this._HTMLDom = null;
		
		this._init();
	}
	
	clsBookingTitle.prototype = {
		_init: function(){
			var $layer = $("div#container>section#main_content>div.golf_board article.depth2_tab");
			
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.data("idx", null); // 인덱스로 관리
			
			this.display();
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setIdx: function(val){
			var $layer = this.$getLayer();
			
			if(val == $layer.data("idx")) return false;
			
			$layer.data("idx", val);
			
			this.display();
			return true;
		}
		, display: function(){
			var $layer = this.$getLayer();
			var idx = $layer.data("idx");
			
			// 현재 인덱싱된 타이틀만 on설정
			$layer.find("li img").each(function(n){
				var imgSrc = $(this).attr("src");
				var szImgName = imgSrc.replace(/(.*)\/(.*).gif/g, function(){
					return arguments[1] + "/" + arguments[2].replace("_on", "");
				});
				
				$(this).attr("src", szImgName + ((idx == n) ? "_on":"") + ".gif");
			});
		}
	}
	
	// 부킹상세
	function clsBookingInfo()
	{
		this._HTMLDom = null;
		this.infoData = null;
		
		this._init();
	}
	
	clsBookingInfo.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board article.board_view")
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setInfo: function(thisData){
			this.infoData = thisData;
			this.display();
		}
		, setWriter: function(thisData){
			this.infoData["작성자"] = thisData;
			this.displayWriter();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("dl.view_tit dt").contents().eq(0).remove().end().end().prepend(this.infoData["제목"]);
			$layer.find("dl.view_tit dt span").html("(" + this.infoData["댓글수"] + ")");
			$layer.find("dl.view_tit dd span:eq(0) img").attr("src", _gf.getDefaultProfileImage());
			$layer.find("dl.view_tit dd span:eq(1)").html(this.infoData["작성자"]["닉네임"]);
			$layer.find("table thead th:eq(1) span:eq(1)").contents().eq(0).remove().end().end().prepend(this.infoData["작성일"])
			$layer.find("table thead th:eq(1) span:eq(1) span").html(this.infoData["작성시"]);
			$layer.find("table thead th:eq(2) span:eq(1)").html(this.infoData["조회수"]);
			$layer.find("table tbody td div").html(this.infoData["내용"]);
			
			// 이미지 리사이징
			document.objUtil.executeThread(function(){
				return $layer.find("table tbody td img").length;
			}, function(){
				$layer.find("table tbody td img").load( function(){
					if($(this).width() > 650) $(this).width(650);
				});
			});
		}
		, displayWriter: function(){
			var $layer = this.$getLayer();
			var d = this.infoData["작성자"];
			
			$layer.find("dl.view_tit dd span:eq(0) img").attr("src", _gf.filePath2Url(d["이미지"])).error(function(){
				$(this).attr("src", _gf.getDefaultProfileImage());
			});
			$layer.find("dl.view_tit dd span:eq(1)").html(d["닉네임"]).hover(function(){
				_gf.showProfileLayer($(this), d, "right", -270, $(this).height());
			}, function(){
				_gf.closeProfileLayer();
			});
		}
		, spinStart: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("dl:first, table:first").hide();
			if($layer.find(">div#tmpSpin").length == 0){
				$layer.prepend("<div id='tmpSpin' style='position:relative; width:600px; height:100px;'></div>");
			}
			$layer.find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find(">div#tmpSpin").hide().spin(false);
			$layer.find("dl, table").show();
		}
		, $getImages: function(){
			return this._HTMLDom["$layer"].find("table tbody td img")
		}
	}
	
	// 부킹댓글
	function clsBookingCommentList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsBookingCommentList.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board article.board_view div.reply_area");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("dl:first").clone(true)
			}
			
			this.setList([]);
			
			//$layer.find("dl").remove();
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, setWriter: function(key, info){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["키"]+"" == key+"") break;
			}
			
			if(i<this.listData.length){
				this.listData[i]["작성자"] == info;
				this.displayWriter(i);
			}
		}
		, display: function(){
			var $layer = this.$getLayer();
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.find("p.reply_num span").html("(" + this.listData.length + ")");
			
			$layer.find("dl").remove();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("div.reply_regist").before($element.clone(true));
			}
			$layer.find("dl").each(function(n){
				$(this).find("dt:eq(0) img").attr("src", _gf.getDefaultProfileImage());
				$(this).find("p.nickname a").html(thisClass.listData[n]["작성자"]["닉네임"]);
				$(this).find("p.reply_date").contents().filter(function(){
					return (this.nodeType==3);
				}).after(thisClass.listData[n]["작성일"]).remove();
				$(this).find("p.reply_date span").html(thisClass.listData[n]["작성시"]);
				$(this).find("dd div").html(thisClass.listData[n]["내용"]);
				if(thisClass.listData[n]["내꺼"] != "Y") $(this).find("p.reply_del").hide();
			});
		}
		, displayWriter: function(n){
			var $layer = this.$getLayer();
			var $obj = $layer.find("dl").eq(n);
			var d = this.listData[n]["작성자"];
			
			$obj.find("dt:eq(0) img").attr("src", _gf.filePath2Url(d["이미지"])).error(function(){
				$(this).attr("src", _gf.getDefaultProfileImage());
			});
			$obj.find("p.nickname a").html(d["닉네임"]).hover(function(){
				_gf.showProfileLayer($(this), d, "left", 0, $(this).height());
			}, function(){
				_gf.closeProfileLayer();
			});
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			
			if($layer.find("div#tmpSpin").length == 0){
				$layer.find("p.reply_num").after("<div id='tmpSpin' style='position:relative; width:600px; height:100px;'></div>");
			}
			$layer.find("div#tmpSpin").show().spin();
			
			$layer.find("dl").hide();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.find("div#tmpSpin").hide().spin(false);
			
			$layer.find("dl").show();
		}
		, getKey: function(n){
			return this.listData[n]["키"];
		}
	}
	
	// 수정삭제
	function clsAuthButton()
	{
		this._HTMLDom = null;
		this.bAuth = null;
		
		this._init();
	}
	
	clsAuthButton.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board article.btn_area");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("img[alt=수정], img[alt=삭제]").hide();
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setAuth: function(bAuth){
			this.bAuth = bAuth;
			this.display();
		}
		, display: function(){
			if(this.bAuth) this.$getLayer().find("img[alt=수정], img[alt=삭제]").show();
		}
		, $getBtnModify: function(){
			return this._HTMLDom["$layer"].find("a").has("img[alt=수정]");
		}
		, $getBtnDelete: function(){
			return this._HTMLDom["$layer"].find("a").has("img[alt=삭제]");
		}
	}
	
	// 댓글등록
	function clsCommentRegist()
	{
		this._HTMLDom = null;

		this._init();
	}
	
	clsCommentRegist.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.reply_area div.reply_regist");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, reset: function(){
			this.$getLayer().find("textarea").val("");
		}
		, focus: function(){
			this._HTMLDom["$layer"].find("textarea").trigger("focus");
		}
		, getValue: function(){
			return this._HTMLDom["$layer"].find("textarea").val();
		}
		, spinStart: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.children().hide();
			if($layer.find("div#tmpSpin").length == 0){
				$layer.prepend("<div id='tmpSpin' style='position:relative; width:580px; height:100px;' />");
			}
			$layer.find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.children().show();
			$layer.find("div#tmpSpin").hide().spin(false);
		}
	}
	
	function clsComm()
	{
		this.bookingRequest = null;
		this.bookingData = null;
		
		this.bookingCommentList = null;
		this.bookingCommentRequest = null;
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			this.bookingData = {
				"제목": null
				, "댓글수": null
				, "작성자": {
						"아이디": null
						, "이미지": null
						, "닉네임": null
					}
				, "작성일": null
				, "작성시": null
				, "조회수": null
				, "내용": null
			}
			
			this.bookingRequest = {
				"키": null
			}
			
			this.bookingCommentList = [
				{
					"키": null
					, "작성자": {
						"아이디": null
						, "이미지": null
						, "닉네임": null
					}
					, "작성일": null
					, "작성시": null
					, "내용": null
				}
			];
			
			this.bookingCommentRequest = {
				"게시판키": null
			}
		}
		, setBookingRequest: function(key, val){
			this.bookingRequest[key] = val;
		}
		, getBookingInfo: function(){
			var thisClass = this;
			
			//ajax
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": "getDetailBookingBoard"
			}, {
				"board_seq": this.bookingRequest["키"]
				, "modpage_yn": "N"
			}, function(ret){
				if(ret["msp"]["contents"]["serviceResult"] == "00000"){
					var obj = ret["msp"]["contents"]["items"];
					var reg_date = obj["reg__date"]+"";
					var reg_time = obj["reg__time"]+"";
					var fileBean = obj["FileBean"];
					
					var aFileList = [];
					
					if(fileBean){
						for(var i=-0;i<fileBean.length;i++){
							var objFile = fileBean[i]["items"];
							aFileList.push({
								"파일키": objFile["file__seq"]
								, "섬네일": objFile["thumb"]
								, "파일명": objFile["path"] + objFile["save__file__name"]
								, "원본파일명": objFile["orgn__file__name"]
							});
						}
					}
					
					thisClass.bookingData = {
						"결과코드": ret["msp"]["contents"]["serviceResult"]
						, "제목": obj["title"]
						, "작성자": {
							"아이디": obj["reg__id"]
							, "이미지": obj["user__image"]
							, "닉네임": obj["reg__nickname"]
						}
						, "작성일": reg_date.substr(0,4) + "-" + reg_date.substr(4,2) + "-" + reg_date.substr(6,2)
						, "작성시": reg_time.substr(0,2) + ":" + reg_time.substr(2,2)
						, "조회수": obj["hit"]
						, "내용": _util.nvl(obj["content"])
						, "내꺼여부": obj["my__article__yn"]
						, "파일리스트": aFileList
					}
				}else{
					thisClass.bookingData = {
						"결과코드": ret["msp"]["contents"]["serviceResult"]
						, "메시지": document.objGlobal.getResultMsg(ret)
					}
				}
				
				document.objControl.finishBookingInfo();
			});
		}
		, getBookingData: function(){
			return this.bookingData;
		}
		, setBookingCommentRequest: function(key, val){
			this.bookingCommentRequest[key] = val;
		}
		, getBookingCommentList: function(){
			var thisClass = this;
			
			this.bookingCommentList = [];
			
			//ajax
			var serviceName = "getBookingCommentList";
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": serviceName,
				"listcount": 100,
				"currpageno": 1
			}, {
				"board_seq": this.bookingCommentRequest["게시판키"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						var reg_date = obj["reg__date"]+"";
						var reg_time = obj["reg__time"]+"";
						
						thisClass.bookingCommentList.push({
							"결과코드": ret["msp"]["contents"]["serviceResult"]
							, "키": obj["reply__seq"]
							, "작성자": {
								"아이디": obj["reg__id"]
								, "이미지": obj["user__image"]
								, "닉네임": obj["reg__nickname"]
							}
							, "작성일": reg_date.substr(0, 4) + "." + reg_date.substr(4, 2) + "." + reg_date.substr(6, 2)
							, "작성시": reg_time.substr(0, 2) + ":" + reg_time.substr(2, 2)
							, "내용": _util.enter2br(obj["content"])
							, "내꺼": obj["my__article__yn"]
						});
					}
				}
				
				document.objControl.finishBookingCommentList(res);
			});
		}
		, getBookingCommentData: function(){
			return this.bookingCommentList;
		}
		, bookingDelete: function(key){
			var thisClass = this;
			
			//ajax
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": "deleteBookingBoard"
			}, {
				"board_seq": key
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				document.objControl.finishBookingDelete(res);
			});
			
			/*setTimeout(function(){
				var ret = {
					"결과코드": "001"
					, "메시지": null
				}
				
				$(thisClass).trigger("evtFinishBookingDelete", [ret]);
			}, 500);*/
		}
		, bookingCommentSubmit: function(arg){
			var thisClass = this;
			
//			arg = {
//				"게시판키": null
//				, "내용": null
//			}

			// ajax
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": "regBookingComment"
			}, {
				"content": encodeURIComponent(arg["내용"])
				, "board_seq": arg["게시판키"]
			}, function(ret){
				document.objControl.finishBookingCommentSubmit({
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				});
				
				document.objControl.finishBookingCommentSubmit(ret);
			});
		}
		, bookingCommentDelete: function(arg){
			var thisClass = this;
			
//			arg = {
//				"부킹키": null
//				, "댓글키": null
//			}
			
			// ajax
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": "deleteBookingComment"
			}, {
				"board_seq": arg["부킹키"]
				, "reply_seq": arg["댓글키"]
			}, function(ret){
				document.objControl.finishBookingCommentDelete({
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				});
				
				document.objControl.finishBookingCommentSubmit(ret);
			});
		}
	}
	
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objBookingTitle = null;
		this.objBookingInfo = null;
		this.objBookingCommentList = null;
		this.objAuthButton = null;
		this.objCommentRegist = null;

		this.bookingKey = document.objUtil.getParam("q_seq");
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objBookingTitle = new clsBookingTitle();
			this.objBookingInfo = new clsBookingInfo();
			this.objBookingCommentList = new clsBookingCommentList();
			this.objAuthButton = new clsAuthButton();
			this.objCommentRegist = new clsCommentRegist();
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			_util.executeThread(function(){
				for(var key in thisClass._premitStart){
					if(!thisClass._premitStart[key]) return false;
				}
				
				return true;
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;

			// 전체게시글, 내가쓴글
			this.objBookingTitle.$getLayer().on("click", "li", function(){
				var n = thisClass.objBookingTitle.$getLayer().find("li").index($(this));
				
				if(n == 1 && !_util.getCookie("member_id")){
					if(!confirm(_LOGIN_TEXT)){
						return;
					}
					_gf.goLogin();
					return;
				}
				
				document.location.href = "booking.html" + ((n) ? "?q_my=Y":"");
			});
			
			$("div#container section#main_content").on("click", "img[alt=글쓰기], img[alt=목록]", function(){
				var alt = $(this).attr("alt");
				
				switch(alt){
					case "글쓰기":
						thisClass.goWritePage();
						break;
					case "목록":
						thisClass.goListPage();
						break;
				}
			});
			
			this.objAuthButton.$getLayer().on("click", "img[alt='수정'], img[alt='삭제']", function(){
				var alt = $(this).attr("alt");
				
				switch(alt){
					case "수정":
						thisClass.goModifyPage();
						break;
					case "삭제":
						if(!confirm("삭제하시겠습니까?")) return;
				
						document.objGlobal.spinStart("deleting...");
						thisClass.objComm.bookingDelete(thisClass.bookingKey);
						break;
				}
			});
			
			// 댓글삭제
			this.objBookingCommentList.$getLayer().on("click", "img[alt='삭제']", function(){
				var n = this.objBookingCommentList.$getLayer().find("img[alt='삭제']").index($(this));
				var key = thisClass.objBookingCommentList.getKey(n);
				
				if(!confirm("삭제하시겠습니까?")) return;
				
				thisClass.objComm.bookingCommentDelete({
					"부킹키": thisClass.bookingKey
					, "댓글키": key
				});
			});
			
			this.objCommentRegist.$getLayer().on("focus", "textarea", function(){
				if(!_util.getCookie("member_id")){
					if(!confirm(_LOGIN_TEXT)){
						$(this).trigger("blur");
						return;
					}
					_gf.goLogin();
					return;
				}
			});
			
			// 댓글등록
			this.objCommentRegist.$getLayer().on("click", "img[alt='댓글등록']", function(){
				if(!_util.getCookie("member_id")){
					if(!confirm(_LOGIN_TEXT)) return;
					_gf.goLogin();
					return;
				}
				
				if(!_gf.validComment(thisClass.objCommentRegist.getValue())){
					thisClass.objCommentRegist.focus();
					return;
				}
				
				thisClass.objCommentRegist.spinStart();
				
				thisClass.objComm.bookingCommentSubmit({
					"게시판키": thisClass.bookingKey
					, "내용": thisClass.objCommentRegist.getValue()
				});
			});
		}
		, _start: function(){
			// 전체게시글로 default 설정
			this.objBookingTitle.setIdx((_util.getParam("q_my") == "Y") ? 1:0);
			
			// 글정보 받아오기
			if(this.bookingKey){
				this.objBookingInfo.spinStart();
				
				this.objComm.setBookingRequest("키", this.bookingKey);
				this.objComm.getBookingInfo();
				
				// 댓글
				this.objBookingCommentList.spinStart();
				this.objComm.setBookingCommentRequest("게시판키", this.bookingKey);
				this.objComm.getBookingCommentList();
			}
		}
		// 글정보 완료
		, finishBookingInfo: function(){
			var thisClass = this;
			
			var thisData = this.objComm.getBookingData();
				
			this.objBookingInfo.spinEnd();
			
			if(thisData["메시지"]) alert(thisData["메시지"]);
			if(thisData["결과코드"] != "00000"){
				this.gotoList();
				return;
			}
			
			this.objBookingInfo.setInfo(thisData);
			
			//thisClass.objAuthButton.setAuth(document.objUtil.getCookie("member_id") == thisData["작성자"]["아이디"]);
			this.objAuthButton.setAuth((thisData["내꺼여부"] == "Y") ? true:false);
			
			// 작성자 정보
			_gf.getMemberInfo({
				"아이디": thisData["작성자"]["아이디"]
				, "콜백": function(ret, info){
					thisClass.objBookingInfo.setWriter(info);
				}
			});
		}
		// 댓글 완료
		, finishBookingCommentList: function(ret){
			var thisClass = this;
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var thisData = this.objComm.getBookingCommentData();
				
			this.objBookingCommentList.spinEnd();
			this.objBookingCommentList.setList(thisData);
			
			// 작성자 정보
			for(var i=0;i<thisData.length;i++){
				_gf.getMemberInfo({
					"아이디": thisData[i]["작성자"]["아이디"]
					, "키": thisData[i]["키"]
					, "콜백": function(res, info, arg){
						thisClass.objBookingCommentList.setWriter(arg["키"], info)
					}
				});
			}
		}
		// 댓글 작성 완료
		, finishBookingCommentSubmit: function(ret){
			this.objCommentRegist.spinEnd();
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objCommentRegist.reset();
			
			// 댓글
			this.objBookingCommentList.spinStart();
			this.objComm.setBookingCommentRequest("게시판키", this.bookingKey);
			this.objComm.getBookingCommentList();
		}
		// 삭제완료
		, finishBookingDelete: function(ret){
			document.objGlobal.spinEnd();
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;

			this.gotoList();
		}
		// 댓글 삭제완료
		, finishBookingCommentDelete: function(ret){
			document.objGlobal.spinEnd();
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			// 댓글
			this.objBookingCommentList.spinStart();
			this.objComm.setBookingCommentRequest("게시판키", this.bookingKey);
			this.objComm.getBookingCommentList();
		}
		// 리스트이동
		, goListPage: function(){
			document.location.href = "booking.html" + _util.paramStringFilter(["q_seq"]);
		}
		// 수정
		, goModifyPage: function(){
			document.location.href = "booking_write.html" + _util.paramStringFilter();
		}
		// 새글
		, goWritePage: function(){
			if(!_util.getCookie("member_id")){
				if(!confirm(_LOGIN_TEXT)) return;
				_gf.goLogin();
				return;
			}
			
			document.location.href = "booking_write.html" + _util.paramStringFilter(["q_seq"]);
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});